import React, { useRef, useEffect } from 'react';
import { Tabs } from 'antd';
import styles from "../Common.less";
import { useGlobalShare } from "../../models/globalShare";
import TextChatArea from './TextChatArea';
import ChatTabPane from "./ChatTabPane";
import HistoryTabPane from "./HistoryTabPane";
import TemplateTabPane from "./TemplateTabPane";
import ChatDialogModal from "./ChatDialogModal";
import { useChatDialogState } from "./chatDialogState";
import * as commonUtil from "../../utils/commonUtil";

const { TabPane } = Tabs;

const TextChatDialog = (props) => {

    const { themeColor } = useGlobalShare();
    const formRef = useRef(null);
    const {
        historyRecords, setHistoryRecords, load_history_records, showMemoryDetail, memoryDetails, setMemoryDetails,
        activeKey, setActiveKey, sourceId, setSourceId, chatDialogModalVisible, setChatDialogModalVisible, ollamaModels,
        selectedDialogKeys, setSelectedDialogKeys, selectedDialogRows, setSelectedDialogRows, loadOllamaModels,
        loadSettingItem, settingItemMap, onSaveDialog, downloadMemoryDetail, deleteHistoryRecord
    } = useChatDialogState();
    const {
        loading, textChatMessages, setTextChatMessages, libraryVisible, selectedPattern, focusBlurFlag, completeStatus, pageSource,
        patternOptions, documentOptions, selectDocument, selectPattern, workflowGraph, focusBlurTextArea, onSendChat,
        markdownTemplate, setMarkdownTemplate
    } = props;

    useEffect(() => {
        loadOllamaModels();
        loadSettingItem({ "source": "llm" });
        setTextChatMessages && setTextChatMessages([ textChatMessages[0], ...memoryDetails ]);
    }, [memoryDetails]);

    const textChatAreaProps = {
        formRef,
        themeColor,
        loading,
        textChatMessages,
        focusBlurFlag,
        completeStatus,
        pageSource,
        focusBlurTextArea,
        onSendChat: (values, query) => {
            if (!sourceId) {
                values.source_id = commonUtil.generateUUID();
                setSourceId(values.source_id);
            } else {
                values.source_id = sourceId;
            }
            onSendChat(values, query);
        }
    }

    const chatTabPaneProps = {
        pageSource,
        libraryVisible,
        patternOptions,
        documentOptions,
        workflowGraph,
        selectDocument,
        ollamaModels,
        settingItemMap,
        selectPattern: (pattern) => {
            selectPattern(pattern);
            load_history_records({ "source": pageSource, "pattern": pattern });
        }
    }

    const onTabChange = (key) => {
        setActiveKey(key);

        if ("history_dialog" == key) {
            load_history_records({ "source": pageSource });
        }
    }

    const historyTabPaneProps = {
        historyRecords,
        showMemoryDetail,
        createNewDialog: () => {
            setSourceId(commonUtil.generateUUID());
            setMemoryDetails([]);
            setTextChatMessages([ textChatMessages[0] ]);
        },
        showMemoryModal:() => {
            setChatDialogModalVisible(true);
        }
    }

    const templateTabPaneProps = {
        markdownTemplate, setMarkdownTemplate
    }

    const chatDialogModalProps = {
        themeColor,
        chatDialogModalVisible,
        historyRecords,
        selectedDialogRows,
        onSaveDialog,
        rowSelection: {
            selectedRowKeys: selectedDialogKeys,
            selectedRows: selectedDialogRows,
            onChange: (keys, selectedRows) => {
                setSelectedDialogKeys(keys);
                setSelectedDialogRows(selectedRows);
            },
        },
        deleteDialog: () => {
            deleteHistoryRecord();
        },
        closeDialogModal: () => {
            setChatDialogModalVisible(false);
        },
        searchDialogChange: (e) => {
            let value = e.target.value;
            let records = historyRecords.filter(item => item.name.includes(value));
            setHistoryRecords(records);
        },
        onDownload: (record) => {
            downloadMemoryDetail(record);
        }
    }

    return (
        <div style={{ width: "100%", height: "100%", display: "flex", flexDirection: "row" }}>
            <div style={{ flex: 5, width: "100%", height: "100%", margin: "0px 20px 0px 0px", background: "#ffffff" }}>
                <TextChatArea { ...textChatAreaProps }  />
            </div>
            <div style={{ width: "350px", lineHeight: 4, background: "#ffffff", padding: "0px 20px 0px 0px" }}>
                <Tabs className={styles.rag_tab_list} onChange={onTabChange}>
                    <TabPane key="rag_setting" tab={"检索设置"}>
                        <ChatTabPane ref={formRef} { ...chatTabPaneProps } />
                    </TabPane>
                    <TabPane key="history_dialog" tab={"历史对话"}>
                        <HistoryTabPane { ...historyTabPaneProps } />
                    </TabPane>
                    {
                        "topic, custom".includes(pageSource) &&
                        <TabPane key="output_template" tab={"输出模版"}>
                            <TemplateTabPane { ...templateTabPaneProps } />
                        </TabPane>
                    }
                </Tabs>
            </div>

            <ChatDialogModal { ...chatDialogModalProps } />
        </div>
    );
}

export default TextChatDialog;
